package com.frogs.ucenter.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.jsoup.Connection.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.PageTurn;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.web.api.entity.ApiUrl;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.ucenter.service.AbsService;
import com.frogs.ucenter.service.TaskService;

@Service("taskService")
public class TaskServiceImpl extends AbsService implements TaskService {

	private static Logger log = LoggerFactory.getLogger(TaskServiceImpl.class);
	
	@Override
	public PageList<Map<String,Object>> getTotalFlowList(Integer userId,
			Integer status, Integer pageNo, Integer pageSize) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("TOTAL_FLOW_LIST");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.status.getParamName(), status.toString(),
				ApiUrlParamEnum.pageNo.getParamName(), pageNo.toString(),
				ApiUrlParamEnum.pageSize.getParamName(), pageSize.toString(),
				};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		PageList<Map<String,Object>> result = new PageList<Map<String,Object>>();
		JSONObject jsonObjectResult = null;
		try{
			jsonObjectResult = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != jsonObjectResult.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(jsonObjectResult.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
			List<Map<String, Object>> list = jsonObjectResult.getJSONObject("response").getObject("list", List.class);
			result.addAll(list);
			JSONObject pageTurnJSONObject = jsonObjectResult.getJSONObject("response").getJSONObject("pageTurn");
	    	result.setPageTurn(JSON.toJavaObject(pageTurnJSONObject, PageTurn.class));
		} catch (IllegalStateException e) {
			log.error("func[getTotalFlowList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("获取主线列表接口异常！");
		}
		return result;
	}
	
	@Override
	public PageList<Map<String,Object>> getSubFlowList(Integer totalFlowId, Integer userId,
			Integer status, Integer pageNo, Integer pageSize) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("SUB_FLOW_LIST");
		String[] otherParams = {
				ApiUrlParamEnum.totalFlowId.getParamName(), totalFlowId.toString(),
				ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.status.getParamName(), status.toString(),
				ApiUrlParamEnum.pageNo.getParamName(), pageNo.toString(),
				ApiUrlParamEnum.pageSize.getParamName(), pageSize.toString(),
				};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		PageList<Map<String,Object>> result = new PageList<Map<String,Object>>();
		JSONObject jsonObjectResult = null;
		try{
			jsonObjectResult = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != jsonObjectResult.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(jsonObjectResult.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
			List<Map<String, Object>> list = jsonObjectResult.getJSONObject("response").getObject("list", List.class);
			result.addAll(list);
			JSONObject pageTurnJSONObject = jsonObjectResult.getJSONObject("response").getJSONObject("pageTurn");
	    	result.setPageTurn(JSON.toJavaObject(pageTurnJSONObject, PageTurn.class));
		} catch (IllegalStateException e) {
			log.error("func[getSubFlowList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("获取子线列表接口异常！");
		}
		return result;
	}
	
	@Override
	public JSONObject getFlowTaskInfoList(Integer subFlowId, Integer userId,
			Integer pageNo, Integer pageSize) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("FLOW_TASK_INFO_LIST");
		String[] otherParams = {
				ApiUrlParamEnum.subFlowId.getParamName(), subFlowId.toString(),
				ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.pageNo.getParamName(), pageNo.toString(),
				ApiUrlParamEnum.pageSize.getParamName(), pageSize.toString(),
				};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		
		JSONObject jsonObjectResult = null;
		try{
			jsonObjectResult = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != jsonObjectResult.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(jsonObjectResult.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[getTotalFlowList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("获取任务列表接口异常！");
		}
		return jsonObjectResult;
	}
	
	/**
	 * 获取所有的常规任务
	 */
	@Override
	public PageList<Map<String,Object>> getPointTaskInfoList(Integer userId, Integer levelId , Integer pageNo , Integer pageSize) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("POINT_TASK_INFO_LIST");
		String[] otherParams = {
				ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.level.getParamName(), levelId.toString(),
				ApiUrlParamEnum.pageNo.getParamName(), pageNo.toString(),
				ApiUrlParamEnum.pageSize.getParamName(), pageSize.toString(),
				
		};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		PageList<Map<String,Object>> result = new PageList<Map<String,Object>>();
		JSONObject jsonObjectResult = null;
		try{
			jsonObjectResult = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != jsonObjectResult.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(jsonObjectResult.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
			List<Map<String, Object>> list = jsonObjectResult.getJSONObject("response").getObject("list", List.class);
			result.addAll(list);
			JSONObject pageTurnJSONObject = jsonObjectResult.getJSONObject("response").getJSONObject("pageTurn");
	    	result.setPageTurn(JSON.toJavaObject(pageTurnJSONObject, PageTurn.class));
		} catch (IllegalStateException e) {
			log.error("func[getPointTaskInfoList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("获取常规任务列表接口异常！");
		}
		return result;
	}
	
	/**
	 * 获取常规任务进度列表
	 */
	@Override
	public List<Map<String, Object>> getPointTaskInfoProgressList(Integer taskId, Integer userId) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("POINT_TASK_PROGRESS_LIST");
		String[] otherParams = {
				ApiUrlParamEnum.taskId.getParamName(), taskId.toString(),
				ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				
		};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		JSONObject jsonObjectResult = null;
		try{
			jsonObjectResult = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != jsonObjectResult.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(jsonObjectResult.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
			result = jsonObjectResult.getJSONObject("response").getObject("list", List.class);
		} catch (IllegalStateException e) {
			log.error("func[getPointTaskInfoProgressList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("获取常规任务进度列表接口异常！");
		}
		return result;
	}
	
	@Override
	public JSONObject startTask(Integer userId, Integer totalFlowId, Integer levelId) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("TASK_START");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.totalFlowId.getParamName(), totalFlowId.toString(),
				ApiUrlParamEnum.level.getParamName(), levelId.toString(),
				};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
		} catch (IllegalStateException e) {
			log.error("func[startTask] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("任务开始接口异常！");
		}
		return result;
	}
	
	@Override
	public JSONObject completeTask(Integer userId, Integer taskCompleteInfoId, Integer taskType, Integer taskInfoId) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("TASK_COMPLETE");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.taskCompleteInfoId.getParamName(), taskCompleteInfoId.toString(),
				ApiUrlParamEnum.taskId.getParamName(), taskInfoId.toString(),
				ApiUrlParamEnum.taskType.getParamName(), taskType.toString(),
				};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
		} catch (IllegalStateException e) {
			log.error("func[completeTask] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("任务完成接口异常！");
		}
		return result;
	}

	@Override
	public JSONObject taskCompleteRate(Integer userId, Integer level)
			throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("TASK_COMPLETE_RATE");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.level.getParamName(), level.toString(),
				};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
		} catch (IllegalStateException e) {
			log.error("func[taskCompleteRate] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("主线任务完成类接口异常！");
		}
		return result;
	}

	@Override
	public JSONObject getTask(Integer userId, Integer taskId)
			throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("GET_TASK");
		String[] otherParams = {
				ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.taskId.getParamName(), taskId.toString(),
				};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
		} catch (IllegalStateException e) {
			log.error("func[getTask] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(), Arrays.deepToString(allParams) , e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("获取任务异常！");
		}
		return result;
	}
}
